import React, { useContext, useState } from 'react'
import classes from './Cart.module.css'
import iconImg from '../../asset/bag.png'
import CartContext from '../../store/CartContext'
import CartDetails from './CartDetails/CartDetails'
import Checkout from './Checkout/Checkout'

const Cart = () => {

    const ctx = useContext(CartContext)
    const [showDetails, setShowDetails] = useState(false)

    const [showCheckout, setShowCheckout] = useState(false)


    // if (ctx.totalAmount === 0) {
    //     setShowDetails(false)
    // }

    const togleDetails = () => {
        if (ctx.totalAmount === 0) return
        setShowDetails(preState => !preState)
    }

    const showCheckoutHandler = () => {
        if (ctx.totalAmount === 0) return
        setShowCheckout(true)
    }

    const hideCheckoutHandler = () => {
        setShowCheckout(false)
    }
    return (
        <div className={classes.Cart} onClick={togleDetails}>
            {showCheckout && <Checkout onHide={hideCheckoutHandler} />}
            {showDetails && <CartDetails />}
            <div className={classes.Icon}>
                <img src={iconImg} alt="" />
                {ctx.totalAmount === 0 ?
                    null : <span className={classes.TotalAmount}>{ctx.totalAmount}</span>
                }

            </div>
            {ctx.totalPrice === 0 ?
                <p className={classes.NoMeals}>未选购商品</p> : <p className={classes.Price}>{ctx.totalPrice}</p>
            }

            <button onClick={showCheckoutHandler} className={`${ctx.totalPrice === 0 ? classes.Disabled : classes.Button} `}>去结算</button>
        </div>
    )
}

export default Cart